<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="55%" @close="handleClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px" class="demo-ruleForm">
                
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <!-- <el-form-item label="内容" prop="text">
                    <el-input type="textarea" v-model="form.text"></el-input>
                </el-form-item> -->
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" maxlength="500" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="imgDtos">
                    <el-upload :action="imageUploadUrl" list-type="picture-card" :file-list="fileList"
                        :on-remove="handleRemove" :on-success="handleAvatarSuccess">
                        <i slot="default" class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <!-- <el-form-item label="内容" prop="text">
                    <quill-editor ref="myTextEditor" v-model="form.text"
                        :options="editorOption"></quill-editor> -->
                    <!-- 富文本图片上传
                    <el-upload :action="imageUploadUrl" :on-success="onsuccess3" list-type="picture-card"
                        id="uploadImage" style="display:none">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item> -->
                <el-form-item label="内容" prop="text">
                            <div style="border: 1px solid #ccc;width:98%;line-height:21px;">
                                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
                                    :defaultConfig="toolbarConfig" :mode="mode" />
                                <Editor  v-if="dialogVisible" style="height: 500px; overflow-y: hidden;" v-model="form.text"
                                    :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
                            </div>
                        </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { specificationAdd, specificationEdit, specificationDetail } from "@/request/api/specification"
// import { getBuildData } from "@/request/api/building"
import rulesUtil from "@/utils/rules"//引入
import { quillEditor, Quill } from "vue-quill-editor";
import { container, ImageExtend } from "quill-image-extend-module";
Quill.register("modules/ImageExtend", ImageExtend);
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {getUploadImg} from "@/request/api/link"
import "quill/dist/quill.bubble.css";
import Parchment from 'parchment';
//目的是修改富文本内容居中不了的问题
let config = {
  scope: Parchment.Scope.BLOCK,
  whitelist: ['right', 'center', 'justify']
};
let AlignStyle = new Parchment.Attributor.Style('align', 'text-align', config);
export { AlignStyle };
var Align = Quill.import('attributors/style/align');
Align.whitelist = ['right', 'center', 'justify'];
Quill.register(Align, true);
export default {
    
    components: { quillEditor, Editor, Toolbar },
    data() {
        return {
            // toolbarConfig: {//工具栏配置
            //     excludeKeys:[
            //         'insertTable',//插入表格
            //     ]
            // },
            dialogVisible: false,
            fileList: [],

            type: "",
            title: "",
            form: {
                id:"",
                 // name: '',//连接名称
                // lyTp:"",//路演中心图片
                title:"",//路演中心标题可作为筛选条件
                text:"",//路演中心文本内容
                remark:"",//备注
                    imgDtos: [ //图片
                        // { "imgUrl": "tupianweizhi1" },
                        // // {"imgUrl":"图片2" },
                    ],

            },
            imgUrl: '',
            rules: {
                
                text: [
                    { required: true, message: '请输入内容', trigger: 'blur' },
                ],
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                ],
                galleryful: [
                    { required: true, validator: rulesUtil.FormValidate.Form().checkInterNumRequired, trigger: 'blur' },
                ],

            },
            imageUploadUrl: '/dev-api/file/upload/uploadNotQR',
            editor: null,
            toolbarConfig: {//工具栏配置
                excludeKeys:[
                    'insertTable',//插入表格
                ]
            },
            editorConfig: {
                placeholder: '请输入内容...',
                // 所有的菜单配置，都要在 MENU_CONF 属性下
                MENU_CONF: {
                    //配置上传图片
                    uploadImage: {
                        customUpload: this.uploadImg
                    },
                    //配置上传视频
                    uploadVideo: {
                        customUpload: this.uploadVideo
                    }
                },
            },
            mode: 'default', // or 'simple'
            dataTree: [],
            selectCate: {
                checkStrictly: false,
                label: "categoryName",
                children: "children",
                value: "id",
                getCheckedNodes: true,
                expandTrigger: "hover",
                emitPath: true
            },
            editorOption: {
                // 富文本框配置
                placeholder: "编辑文章内容",
                theme: "snow", // or 'bubble'
                modules: {
                    toolbar: {
                        container: container, // 工具栏
                        handlers: {
                            image: function (value) {
                                if (value) {
                                    document.querySelector("#uploadImage input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },
        };
    },

    methods: {
        open(type, info) {
            this.type = type;
            this.dialogVisible = true;
            this.fileList = []
            this.form.imgDtos = []
            if (this.type === "add") {
                this.title = "新增功能说明";
                let params = {
                    id:"",
                 // name: '',//连接名称
                // lyTp:"",//路演中心图片
                title:"",//路演中心标题可作为筛选条件
                text:"",//路演中心文本内容
                remark:"",//备注
                    imgDtos: [ //图片
                        // { "imgUrl": "tupianweizhi1" },
                        // // {"imgUrl":"图片2" },
                    ],

                }
                this.form = params
                this.fileList = []

            } else if (this.type === "edit") {
                this.title = "修改功能说明";
                // this.form = info
                this.getDetail(info.id)

            }
        },
        // 区划
        selectValue(val) {
            this.$refs.cascader2.dropDownVisible = false;
        },
        handleClose() {
            this.$emit('getTrain')
            this.$refs.form.resetFields();
            const editor = this.editor
            if (editor == null) return
            editor.destroy() // 组件销毁时，及时销毁编辑器

        },
        // 查看详情
        getDetail(id) {
            let params = {
                id
            }
            specificationDetail(params).then(res => {
                if (res.data.code === 200) {
                    var imgs = res.data.result.imgDtos
                    this.form = res.data.result
                    imgs.forEach(item => {
                        this.fileList.push({
                            url: item.imgUrl,
                            id: item.id
                        })
                    })
                }

            })
        },
        // 创建
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    if (this.type === 'add') {
                        let params = { ...this.form }
                        specificationAdd(params).then((res) => {
                            loading.close();
                            if (res.data.code === 200) {
                                this.$message({
                                    message: res.data.message,
                                    type: "success",
                                });
                                this.dialogVisible = false
                                 

                            } else {
                                this.$message.error(res.data.message);
                            }
                        });
                    } else if (this.type === 'edit') {
                        var imgList = this.form.imgDtos
                        var newImg=[]
                        imgList.forEach(item => {
                            newImg.push({
                                imgUrl: item.imgUrl,
                                imgName: item.imgName
                            })
                        })
                        let params = { ...this.form }
                        params.imgDtos=newImg
                        specificationEdit(params).then((res) => {
                            loading.close();
                            if (res.data.code === 200) {
                                this.$message({
                                    message: res.data.message,
                                    type: "success",
                                });
                                this.dialogVisible = false
                                 

                            } else {
                                this.$message.error(res.data.message);
                            }
                        });
                    }
                } else {
                    return false;
                }
            });
        },
        // 文件上传删除
        handleRemove(response) {
            var dataList = this.form.imgDtos;
            if (response.id) {
                for (var i = 0; i < dataList.length; i++) {
                    if (dataList[i].id.indexOf(response.id) > -1) {
                        var index = i;
                        dataList.splice(index, 1); //存在即删除
                    }
                }
            } else {
                for (var j = 0; j < dataList.length; j++) {
                    if (dataList[j].imgName.indexOf(response.name) > -1) {
                        var index2 = j;
                        dataList.splice(index2, 1); //存在即删除
                    }
                }
            }
            this.form.imgDtos = dataList
        },
        handleDownload(file) {

        },
        // 上传成功
        handleAvatarSuccess(response, file, fileList) {
            this.form.imgDtos.push({
                imgUrl: response.message,
                imgName: file.name,
            })
        },
        // 上传文件失败
        handleError(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        // 限制上传的类型
        beforeAvatarUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过 10M!");
                return false;
            }
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "jpg" || testmsg === "JPG";
            const extension2 = testmsg === "png" || testmsg === "PNG";
            if (!extension && !extension2) {
                this.$message({
                    message: "上传图片只能是 jpg, png格式!",
                    type: "error",
                });
                return false;
            }
        },
         // 富文本的上传图片
         onsuccess3(response, file, fileList) {
            let quill = this.$refs.myTextEditor.quill;
            // 如果上传成功的话
            if (response.code === 200) {
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片，res为服务器返回的图片链接地址
                quill.insertEmbed(length, "image", response.message);
                // 调整光标到最后
                quill.setSelection(length + 1);
            } else {
                // 提示信息，需引入Message
                this.$message({
                    type: "error",
                    message: "图片插入失败！",
                });
            }
        },
        // 富文本
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        // 富文本-上传图片
        uploadImg(file, insertFn){
            let imgData = new FormData();
			imgData.append('file', file);
             //调接口，上传图片
             getUploadImg(imgData).then(response => {
                if(response.data.code == 200){
                    insertFn(response.data.message);
                }else{
                    this.$message.error(response.data.message);
                }
            })
        },
        // 富文本-上传视频
        uploadVideo(file, insertFn){
            let imgData = new FormData();
			imgData.append('file', file);
             //调接口，上传图片
             getUploadImg(imgData).then(response => {
                if(response.data.code == 200){
                    insertFn(response.data.message);
                }else{
                    this.$message.error(response.data.message);
                }
            })
        }
    },
      // 生命周期-离开当前页面路由
      beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less" scoped>
::v-deep .ql-editor{
    min-height: 200px;
}
.el-input {
    width: 380px;
}

.el-cascader {
    width: 380px;
}

.el-textarea {
    width: 380px;
}

.el-radio-group {
    width: 380px;
}

.el-date-editor {
    width: 380px;
}

/deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>

